﻿using Furion;
using Furion.DatabaseAccessor;
using Furion.DataEncryption;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using HOPU.OnlineSchool.Application.Users.Dtos;
using HOPU.OnlineSchool.Core;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace HOPU.OnlineSchool.Application.Users.Services
{
    public class UserService : IUserService, ITransient
    {
        private readonly IRepository<AclUser> _userRepository;

        public UserService(IRepository<AclUser> userRepository)
        {
            _userRepository = userRepository;
        }
        public LoginSuccessDto Info()
        {
            LoginSuccessDto loginDto = new LoginSuccessDto();
            loginDto.Name = App.User?.FindFirstValue("Username");
            loginDto.NickName = App.User?.FindFirstValue("NickName");
            loginDto.Roles = new string[] { App.User?.FindFirstValue("Roles") };
            loginDto.Avatar = App.User?.FindFirstValue("Avatar");

            return loginDto;
        }
        public async Task<LoginJwtDto> LoginAsync(LoginInfoInput input)
        {
            //获取加密后的字符串
            var password = MD5Encryption.Encrypt(input.Password);

            //根据用户名和密码查询用户
            AclUser user = await _userRepository.Where(u => u.Username == input.UserName && u.Password == password).FirstOrDefaultAsync();

            //如果返回为空，则说明用户不存在
            if (user == null) throw Oops.Oh("用户名或密码有误");

            //返回token（临时处理，后续优化）
            // 生成 token
            var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>()
            {
                { "Username", user.Username },  // 存储Id
                { "NickName",user.NickName }, // 存储用户名
                { "Roles","普通管理员" }, // 
                { "Avatar","http://test-onlineshool.oss-cn-beijing.aliyuncs.com/1.jpg" }, // 
            });
            return new LoginJwtDto() { Token = accessToken };
        }

        public string Logout()
        {
            return "退出成功";
        }
    }
}
